import _ from "lodash";


/**
 * 
 * @param {Function} VueComponentFunction Element 挂载到vue组件实例$message函数
 * @param {Array<object>} rules 验证规则
 * @param {any} value 验证参数
 * @returns truthy | falsy
 */
export function validateFileds(VueComponentFunction, rules = [], value) {
    const rule = _.find(rules, ['required', true]); // Returns the matched element, else undefined.

    if (!_.isObject(rule)) return false;
    const type = rule.type || 'string'
    let array = [];
    for (let i in rules) {
        if (type === 'string') {
            const truthy = validateString(VueComponentFunction, rules[i], value);
            array.push(truthy);
            if(!truthy) break;
        }
        if (type === 'number') {
            const truthy = validateNumber(VueComponentFunction, rules[i], value);
            array.push(truthy);
            if(!truthy) break;
        }
        if (type === 'date') {
            // 验证日期格式
            const truthy = validateDate(VueComponentFunction, rules[i], value);
            array.push(truthy);
            if(!truthy) break;
        }
    }
    return array.every(it => it);
}
/**
 * 
 * @param {Function} VueComponentFunction Element 挂载到vue组件实例$message函数
 * @param {object} rule 验证规则
 * @param {any} value 验证参数
 * @returns true | false
 */
export function validateString(VueComponentFunction, rule, value) {
    if (!_.isString(value)) return false;
    if (!value.length) {
        VueComponentFunction({
            type: 'warning',
            message: rule['message']
        })
        return false;
    }
    if (value.length < rule['min'] || value.length > rule['max']) {
        VueComponentFunction({
            type: 'warning',
            message: rule['message']
        })
        return false;
    }
    return true;
}

/**
 * 
 * @param {Function} VueComponentFunction Element 挂载到vue组件实例$message函数
 * @param {object} rule 验证规则
 * @param {object} value 验证参数
 * @returns true | false
 */
export function validateNumber(VueComponentFunction, rule, value) {
    if (!_.isNumber(value)) return false;
    if (+value < rule['min'] || +value > rule['max']) {
        VueComponentFunction({
            type: 'warning',
            message: rule['message']
        })
        return false;
    }
    return true;
}

/**
 * 
 * @param {Function} VueComponentFunction Element 挂载到vue组件实例$message函数
 * @param {object} rule 验证规则
 * @param {any} value 验证参数
 * @returns true | false
 */
export function validateDate(VueComponentFunction, rule, value) {
    if (!_.isDate(value)) {
        VueComponentFunction({
            type: 'warning',
            message: rule['message']
        })
        return false;
    }
    return true;
}